<script setup lang="ts">

import {ref, reactive} from "vue";
import HexGrid, {HexData} from "@/components/hex/HexGrid.vue";
import {HexGraph} from "@/components/hex/HexGraph";
import {HexMatrix, HexMatrixType} from "@/components/hex/HexMatrix";
import {asleep, range} from "@/components/comm/utils";
import {HexPosition} from "@/components/hex/HexContainer";

const radius = ref(20);
const inclination = ref(30);

const hexGraph = reactive(new HexGraph<HexData>(3, pos => ({
  fill: 'pink',
  text: pos.join(' '),
  onClick: onClick,
})));
const hexMatrix = reactive(new HexMatrix<HexData>(20, 15, HexMatrixType.ODD_R, pos => ({
  fill: 'pink',
  text: pos.join(' '),
  onClick: ripple,
})));

function onWheel(e: WheelEvent) {
  e.preventDefault()          // 需要阻止页面滚动时调用
  const delta = e.deltaY      // 正向向下，负向向上
  radius.value -= delta / 100
}

const output = ref('点击任意块');
const posA = ref<[number, number, number]>();
const posB = ref<[number, number, number]>();

function onClick(pos: HexPosition) {
  if (posA.value && posB.value) {
    hexGraph.get(posA.value).fill = 'pink';
    hexGraph.get(posB.value).fill = 'pink';
    posA.value = undefined;
    posB.value = undefined;
  }
  if (!posA.value) {
    posA.value = pos;
    output.value = `第一次点击：[${pos.join(', ')}]`;
    hexGraph.get(pos).fill = 'green';
  } else {
    posB.value = pos;
    const dis = HexGraph.distance(posA.value, posB.value);
    output.value += `，第二次点击：[${pos.join(', ')}]，距离：${dis}`;
    hexGraph.get(pos).fill = 'red';
  }
}

async function ripple(center: HexPosition): Promise<void> {
  const n = Math.max(hexMatrix.rows, hexMatrix.cols);
  for (const d of range(2 * n)) {
    for (const pos of hexMatrix.spiralIter(center, d, d)) {
      hexMatrix.get(pos).fill = 'yellow';
    }
    await asleep(100);
    for (const pos of hexMatrix.spiralIter(center, d, d)) {
      hexMatrix.get(pos).fill = 'pink';
    }
  }
}


// TODO 整个画布支持移动和旋转操作（需要与inclination和position属性区分开，这两个属性是坐标轴本身的变换，画布操作应当只影响显示）

</script>

<template>
  <div class="main">
    <HexGrid
        :data="hexMatrix"
        :radius="radius"
        :inclination="inclination"
        :center="[20,20]"
        @wheel="onWheel"
    />
    <HexGrid
        :data="hexGraph"
        :radius="radius"
        :inclination="inclination"
        @wheel="onWheel"
    >
      <template #front>
        <text
            :x="100"
            :y="100"
            dominant-baseline="middle"
        >
          {{ output }}
        </text>
      </template>
    </HexGrid>
    <el-row>
      <el-col :span="1">
        <el-text>角度</el-text>
      </el-col>
      <el-col :span="23">
        <el-slider v-model="inclination" show-input :max="360"/>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="1">
        <el-text>半径</el-text>
      </el-col>
      <el-col :span="23">
        <el-slider v-model="radius" show-input :max="360"/>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>

</style>